package com.example.everying.controller.points;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.annotation.WebLog;
import com.example.everying.constant.SysConfigConstants;
import com.example.everying.context.UserContext;
import com.example.everying.model.dto.user.PopupDto;
import com.example.everying.model.entity.user.ActivityParticipation;
import com.example.everying.model.entity.user.ActivityPointsConfig;
import com.example.everying.model.entity.user.UserEntity;
import com.example.everying.model.vo.points.PointsAccountListVO;
import com.example.everying.model.vo.user.UserInfoVo;
import com.example.everying.service.system.SysConfigService;
import com.example.everying.service.user.*;
import com.example.everying.utils.CampusException;
import com.example.everying.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@Api(tags = "积分账户")
@RequestMapping("/points")
public class PointsAccountController {

    @Autowired
    private PointsAccountService pointsAccountService;
    @Autowired
    private ActivityPointsConfigService activityPointsConfigService;
    @Autowired
    private ActivityParticipationService activityParticipationService;
    @Autowired
    private PointsTransactionService points;
    @Autowired
    private UserService userService;
    @Autowired
    private SysConfigService sysConfigService;


    @PostMapping("/user")
    @ApiOperation(value = "获取用户积分")
    @WebLog(description = "获取用户积分")
    public Result<?> points() {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            throw new CampusException("请先登录", 201);
        }
        return Result.ok(pointsAccountService.getByUid(userInfoVo.getId()));
    }

    @PostMapping("/user/2")
    @ApiOperation(value = "创建用户积分")
    @WebLog(description = "创建用户积分")
    public Result<?> pointsss() {
        pointsAccountService.ccccc();
        return Result.ok();
    }

    @PostMapping("/get/activity")
    @ApiOperation(value = "领取活动积分")
    @WebLog(description = "领取活动积分")
    public Result<?> activityPoints(@ApiParam(name = "ActivityParticipation", value = "积分领取记录", required = true)
                                    @RequestBody ActivityParticipation config) {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            throw new CampusException("请先登录", 201);
        }
        ActivityParticipation activityParticipation = activityParticipationService.getById(config.getId());
        if (activityParticipation == null) {
            throw new CampusException("该活动还未完成", 201);
        }
        if (activityParticipation.getStatus().equals("2")) {
            throw new CampusException("该活动已领取", 201);
        }
        // 先查这个文章有没有配置
        QueryWrapper<ActivityPointsConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", activityParticipation.getParticipationType());
        ActivityPointsConfig activityPointsConfig = activityPointsConfigService.getOne(queryWrapper);
        if (activityPointsConfig == null) {
            throw new CampusException("该活动不存在", 201);
        }
        boolean isExist = activityPointsConfigService.checkActivityById(activityPointsConfig.getId());
        if (!isExist) {
            throw new CampusException("活动不存在", 201);
        }
        activityParticipation.setStatus("2");
        pointsAccountService.addPointsAndParticipation(userInfoVo.getId(), activityPointsConfig.getPoints(),
                "活动积分", activityParticipation.getParticipationType(), activityParticipation);

        return Result.ok("领取成功");
    }

    @GetMapping("/activitySelect")
    @ApiOperation(value = "查询新用户是否领取过")
    public Result<?> activitySelect(String status) {
        PointsAccountListVO listVO = new PointsAccountListVO();
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            throw new CampusException("请先登录", 201);
        }
        boolean hasReceived = points.checkUserReceived(userInfoVo.getId(), status);
        listVO.setIsAdd(hasReceived);
        listVO.setUser(userInfoVo.getId());

        return Result.ok(listVO);
    }

    @PostMapping("/getPoints")
    @ApiOperation(value = "领取注册奖励积分")
    @WebLog(description = "领取注册奖励积分")
    public Result<?> getPoints(@ApiParam(name = "ActivityPointsConfig", value = "领取注册奖励积分", required = true)
                               @RequestBody ActivityPointsConfig config) {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            throw new CampusException("请先登录", 201);
        }
        QueryWrapper<UserEntity> user = new QueryWrapper<>();
        user.eq("id", userInfoVo.getId());
        user.eq("is_delete", 0);
        UserEntity userEntity = userService.getOne(user);
        if (userEntity == null) {
            throw new CampusException("用户信息不存在", 201);
        }
//        if (userEntity.getIsFirst() == 0) {
//            throw new CampusException("您已不是新用户，无法参与该活动", 201);
//        }
        boolean hasReceived = points.checkUserReceived(userInfoVo.getId(), "2");
        if (!hasReceived) {
            log.info("用户[{}]已领取过该活动积分", userInfoVo.getId());
            return Result.ok("您已领取过该活动积分，无法重复领取");
        }
        QueryWrapper<ActivityPointsConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", "6");
        ActivityPointsConfig activityPointsConfig = activityPointsConfigService.getOne(queryWrapper);
        if (activityPointsConfig == null) {
            throw new CampusException("该活动不存在", 201);
        }
        boolean isExist = activityPointsConfigService.checkActivityById(activityPointsConfig.getId());
        if (!isExist) {
            throw new CampusException("活动不存在", 201);
        }
        pointsAccountService.addPoints(userInfoVo.getId(), activityPointsConfig.getPoints(), "用户注册奖励积分", activityPointsConfig.getType());

        return Result.ok("领取成功");
    }

    @PostMapping("/activityList")
    @ApiOperation(value = "给用户批量发送活动积分")
    public Result<?> activityList(@RequestBody PointsAccountListVO listVO) {
        boolean b = pointsAccountService.activityList(listVO.getUserId(), listVO.getPoints());
        if (!b) {
            return Result.fail("发送失败");
        }
        return Result.ok();
    }


    @GetMapping("/checkNewUser")
    @ApiOperation(value = "获取是否是新用户和文章id")
    @WebLog(description = "获取是否是新用户和文章id")
    public Result<?> checkNewUserWithArticle(HttpServletRequest request) {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            throw new CampusException("请先登录", 201);
        }
        PopupDto popupDto = new PopupDto();
        if (userInfoVo.getIsFirst() == 0) {
            // 新用户
            popupDto.setNewUser(true);
        } else {
            popupDto.setNewUser(false);
        }
        userInfoVo = userService.getUserById(userInfoVo.getId());
        popupDto.setPopupClosed(userInfoVo.isPopupClosed());
        // 从配置表获取文章ID
        String articleId = sysConfigService.getConfigValue(SysConfigConstants.TUTORIAL_ARTICLE_ID);
        popupDto.setArticleId(articleId);
        // 更新缓存
        String token = request.getHeader("Authorization");
        userService.saveTokenHash(userInfoVo,token);
        return Result.ok(popupDto);
    }

    @PostMapping("/closePopup")
    @ApiOperation(value = "关闭弹窗")
    @WebLog(description = "关闭弹窗")
    public Result<?> closePopup() {
        UserInfoVo userInfoVo = UserContext.getUser();
        if (userInfoVo == null) {
            throw new CampusException("请先登录", 201);
        }
        boolean bool = userService.closePopup(userInfoVo.getId());
        if (!bool) {
            return Result.fail("关闭失败");
        }
        return Result.ok();
    }

}
